package com.ovo.rxandroiddemo.utils;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ovo.rxandroiddemo.R;

/**
 * 获取验证码倒计时
 */
public class GETCodeUtils {

    private static long timeOut = 0;//验证码超时时间
    private static int timeOutNumTotal = 60;//设置超时时间
    private static int timeOutNum = 60;//设置超时时间

    private static final int TIME_OUT = 1;
    private static MyHandler handler;

    private static TextView getCode;

    private static class MyHandler extends Handler{

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TIME_OUT:
                    if (getCode == null)break;
                    if (timeOutNum < 0){
                        getCode.setEnabled(true);
                        removeCallbacks(myRunnable);
                        getCode.setText(R.string.get_code);
                        timeOutNum = timeOutNumTotal;
                    }else {
                        getCode.setText(String.valueOf(timeOutNum) + "s");
                        timeOutNum --;
                    }
                    break;
            }
        }
    }

    private static Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - timeOut > 950){
                timeOut = System.currentTimeMillis();
                handler.sendEmptyMessage(TIME_OUT);
            }
            handler.postDelayed(this, 100);
        }
    };

    public static void startCode(TextView getCodes){
        timeOutNumTotal = 60;
        timeOutNum = 60;
        handler = new MyHandler();
        getCode = getCodes;
        handler.postDelayed(myRunnable, 10);
        getCode.setEnabled(false);
    }

    public static void endCode(){
        handler.removeCallbacks(myRunnable);
    }

}
